import React, { useRef, useState, useEffect } from 'react';
import NoUiSlider from '../../components/NoUiSlider';
import './styles.css';

const InputSlider = () => {
  const containerRef = useRef(null);
  const [values, setValues] = useState([20, 80]);

  useEffect(() => {
    if (containerRef.current) {
      const slider = containerRef.current.querySelector('.noUi-target');
      if (slider) {
        // 监听滑块更新事件
        slider.addEventListener('update', (e) => {
          setValues(e.detail);
        });
      }
    }
  }, []);

  const handleInputChange = (index, value) => {
    const newValues = [...values];
    newValues[index] = Number(value);
    setValues(newValues);
    
    if (containerRef.current) {
      const slider = containerRef.current.querySelector('.noUi-target');
      if (slider && slider.noUiSlider) {
        slider.noUiSlider.set(newValues);
      }
    }
  };

  const handleKeyPress = (e, index) => {
    if (e.key === 'Enter') {
      const input = e.target;
      const value = Number(input.value);
      if (!isNaN(value)) {
        handleInputChange(index, value);
      }
    }
  };

  const handleEnd = (values) => {
    console.log('输入框联动滑块结束时的值:', values);
    console.log('输入框联动滑块范围:', {
      min: 0,
      max: 100,
      current: values
    });
  };

  return (
    <div className="input-slider-container">
      <h2>HTML5 Input Types Example</h2>
      <div className="slider-wrapper">
        <div className="slider-container" ref={containerRef}>
          <NoUiSlider
            start={values}
            connect={true}
            range={{
              min: 0,
              max: 100
            }}
            tooltips={true}
            onEnd={handleEnd}
          />
        </div>
      </div>
      <div className="input-wrapper">
        <input
          type="number"
          className="input-with-keypress"
          value={values[0]}
          min="0"
          max="100"
          step="1"
          onChange={(e) => handleInputChange(0, e.target.value)}
          onKeyPress={(e) => handleKeyPress(e, 0)}
        />
        <input
          type="number"
          className="input-with-keypress"
          value={values[1]}
          min="0"
          max="100"
          step="1"
          onChange={(e) => handleInputChange(1, e.target.value)}
          onKeyPress={(e) => handleKeyPress(e, 1)}
        />
      </div>
      <p className="description">
        使用方向键或直接输入数值来调整滑块。按回车键确认输入。
      </p>
    </div>
  );
};

export default InputSlider; 